//
//  ConfigZhuangViewController.m
//  customer
//
//  Created by 往返网络 on 17/8/23.
//  Copyright © 2017年 com. All rights reserved.
//

#import "ConfigZhuangViewController.h"
#import "SuccedZhuanViewController.h" //转账成功
#define return_tag 1000
#define config_tag 1001
#define yanzheng_tag 1002
#define min_h 80.0/H_BASE*SCREEN_H
//定义发送验证码URL
#define URL_GETCODE [NSString stringWithFormat:@"%@/Appcustomernewer/Pay/payTransferThirdSend?",BASE_URL]
//定义确认转账URL
#define URL_CONFIGZHUAN [NSString stringWithFormat:@"%@/Appcustomernewer/Pay/payTransferThirdConfig?type=get",BASE_URL]

@interface ConfigZhuangViewController ()<UITextFieldDelegate>
//开辟多线程定时器，在后台执行，比NSTimer更自然
@property (nonatomic,strong) dispatch_source_t timer;
@property (nonatomic,strong)AFHTTPSessionManager* manger;
@property (nonatomic,copy)NSString * sendcode; //点击发送验证码
@property (nonatomic,strong)NSDictionary * info; //确认信息info
@end
@implementation ConfigZhuangViewController
{
    UILabel * userlab;//表明是货主还是专线
    UILabel * userphonelab; //账户号
    UITextField * messagetf; //验证码TF
    UIButton * messbtn; //验证码btn
  

}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    // Do any additional setup after loading the view.
}
- (void)createUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    float fontsize = 17;
    
    fontsize = SCREEN_H < 667 ? 15 : 19;
    
    if (SCREEN_H == 667) {
        
        fontsize = 17;
    }
    self.view.backgroundColor = COLORRGBA(239, 239, 239, 1);
    //设置表头
    UIView * titleview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 128.0/1334*SCREEN_H)];
    
    titleview.backgroundColor = COLORRGBA(7, 24, 57, 1);
    
    [self.view addSubview:titleview];
    
    //title
    UILabel * titlelab = [[UILabel alloc]initWithFrame:CGRectMake(0, 20.0, SCREEN_W, 90.0/H_BASE*SCREEN_H)];
    titlelab.text = @"转账信息确认";
    titlelab.textColor = [UIColor whiteColor];
    [self.view addSubview:titlelab];
    titlelab.textAlignment = NSTextAlignmentCenter;
    titlelab.font = [UIFont systemFontOfSize:fontsize];
    
    UILabel * leftlable  = [[UILabel alloc]initWithFrame:CGRectMake(0, 20+14.0/1334*SCREEN_H, 150.0/W_BASE*SCREEN_W, 60.0/1334.0*SCREEN_H)];
    leftlable.textAlignment = NSTextAlignmentCenter;
    NSString * endstr = @"\U0000e697";
    NSString * text = [NSString stringWithFormat:@"%@%@",endstr,@"返回"];
    leftlable.attributedText = [self changeLabelWithText2:text andStartplace:endstr andendplae:nil andfontsize:fontsize-2];
    leftlable.textColor = [UIColor whiteColor];
    [self.view addSubview:leftlable];
    
    UIButton * returnbtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150.0/W_BASE*SCREEN_W, 150.0/H_BASE*SCREEN_H)];
    [returnbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    returnbtn.tag = return_tag;
    [self.view addSubview:returnbtn];
    
    //转账用户
    UIView * view1 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(titleview.frame)+20.0/H_BASE*SCREEN_H, SCREEN_W,min_h )];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
    
    userlab = [[UILabel alloc]initWithFrame:CGRectMake(20.0/W_BASE*SCREEN_W, 0, 300.0/W_BASE*SCREEN_W, min_h)];
    if ([self.user_type isEqualToString:@"1"]) {
        userlab.text = @"对方帐号信息(货主)";
    }else if ([self.user_type isEqualToString:@"2"]){
        userlab.text = @"对方帐号信息(专线)";
    }
    NSString * text1 = @"对方帐号信息";
    NSString * endstr1 = [NSString stringWithFormat:@"%@",@"(货主)"];
    userlab.attributedText = [self changeLabelWithText:userlab.text andStartplace:text1 andendplae:endstr1 andfontsize:fontsize-2];
    userlab.textAlignment = NSTextAlignmentLeft;
    [view1 addSubview:userlab];
    userlab.font = [UIFont systemFontOfSize:fontsize-2];
    
    userphonelab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_W - 320.0/W_BASE*SCREEN_W, 0, 300.0/W_BASE*SCREEN_W, min_h)];
    if ([self.user_name isEqualToString:@""]) {
        userphonelab.text = [NSString stringWithFormat:@"%@",self.phonestring];
    }else{
        userphonelab.text = [NSString stringWithFormat:@"%@(%@)",self.phonestring,self.user_name];
    
    }
    userphonelab.font = [UIFont systemFontOfSize:fontsize-2];
    [view1 addSubview:userphonelab];
    userphonelab.textAlignment = NSTextAlignmentRight;
    
    UIView * view2 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(view1.frame)+20.0/H_BASE*SCREEN_H, SCREEN_W,min_h )];
    view2.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view2];

    UILabel * zhuanlab = [[UILabel alloc]initWithFrame:CGRectMake(20.0/W_BASE*SCREEN_W, 0, 300.0/W_BASE*SCREEN_W, min_h)];
    zhuanlab.textAlignment = NSTextAlignmentLeft;
    zhuanlab.textColor = COLORRGBA(102, 102, 102, 1);
    zhuanlab.text = @"转账金额(元)";
    zhuanlab.font = [UIFont systemFontOfSize:fontsize-2];
    [view2 addSubview:zhuanlab];
    
    UILabel * jinelab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_W - 320.0/W_BASE*SCREEN_W, 0, 300.0/W_BASE*SCREEN_W, min_h)];
    jinelab.text = [NSString stringWithFormat:@"%@",self.jinestring];
    jinelab.font = [UIFont systemFontOfSize:fontsize-2];
    [view2 addSubview:jinelab];
    jinelab.textAlignment = NSTextAlignmentRight;
    
    UIView * view3 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(view2.frame)+20.0/H_BASE*SCREEN_H, SCREEN_W,min_h )];
    view3.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view3];
    
    UILabel * phonelab = [[UILabel alloc]initWithFrame:CGRectMake(20.0/W_BASE*SCREEN_W, 0, 300.0/W_BASE*SCREEN_W, min_h)];
    phonelab.textAlignment = NSTextAlignmentLeft;
    phonelab.textColor = COLORRGBA(102, 102, 102, 1);
    phonelab.text = @"手机号";
    phonelab.font = [UIFont systemFontOfSize:fontsize-2];
    [view3 addSubview:phonelab];
    
    UILabel * phonenum = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_W - 320.0/W_BASE*SCREEN_W, 0, 300.0/W_BASE*SCREEN_W, min_h)];
    NSString  * phone = self.sendphone;
    NSString * startstr = [phone substringToIndex:3];
    NSString * endstring = [phone substringFromIndex:7];
    phonenum.textAlignment = NSTextAlignmentRight;
    phonenum.text  = [NSString stringWithFormat:@"%@****%@",startstr,endstring];
    phonenum.font = [UIFont systemFontOfSize:fontsize-2];
    [view3 addSubview:phonenum];
    phonenum.textAlignment = NSTextAlignmentRight;

    UIView * view4 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(view3.frame)+20.0/H_BASE*SCREEN_H, SCREEN_W,min_h )];
    view4.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view4];
    
    UILabel * yanzhenglab = [[UILabel alloc]initWithFrame:CGRectMake(20.0/W_BASE*SCREEN_W, 0, 300.0/W_BASE*SCREEN_W, min_h)];
    yanzhenglab.textAlignment = NSTextAlignmentLeft;
    yanzhenglab.textColor = COLORRGBA(102, 102, 102, 1);
    yanzhenglab.text = @"验证码";
    yanzhenglab.font = [UIFont systemFontOfSize:fontsize-2];
    [view4 addSubview:yanzhenglab];
    
    messagetf = [[UITextField alloc]initWithFrame:CGRectMake(130.0/W_BASE*SCREEN_W, 0, 150.0/W_BASE*SCREEN_W, min_h)];
    messagetf.font = [UIFont systemFontOfSize:fontsize-2];
    messagetf.delegate = self;
    messagetf.keyboardType = UIKeyboardTypeNumberPad;
    [view4 addSubview:messagetf];
    
    messbtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_W- 180.0/W_BASE*SCREEN_W, CGRectGetMinY(messagetf.frame)+10.0/H_BASE*SCREEN_H, 150.0/W_BASE*SCREEN_W, 60.0/H_BASE*SCREEN_H)];
    messbtn.layer.cornerRadius = 2;
    messbtn.layer.borderColor = [COLORRGBA(255, 102, 102, 1)CGColor];
    messbtn.layer.borderWidth = 1;
    messbtn.clipsToBounds = YES;
    messbtn.backgroundColor = [UIColor whiteColor];
    messbtn.clipsToBounds = YES;
    [messbtn setTitleColor:COLORRGBA(255, 102, 102, 1) forState:UIControlStateNormal];
    messbtn.titleLabel.font = [UIFont systemFontOfSize:fontsize - 5];
    [view4 addSubview:messbtn];
    [messbtn setTitle:@"获取验证码" forState:UIControlStateNormal];
     messbtn.tag = yanzheng_tag;
    [messbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * configbtn = [[UIButton alloc]initWithFrame:CGRectMake(30.0/W_BASE*SCREEN_W, CGRectGetMaxY(view4.frame)+30.0/H_BASE*SCREEN_H, SCREEN_W - 60.0/W_BASE*SCREEN_W, min_h)];
    configbtn.backgroundColor = COLORRGBA(59, 214, 117, 1);
    [self.view addSubview:configbtn];
    [configbtn setTitle:@"确认转账" forState:UIControlStateNormal];
    [configbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [configbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    configbtn.tag = config_tag;
    
    
    
}

#pragma mark  -  -  起始地＋发货人名（终止地＋收货人名）格式化 － － －-- - -  -

-(NSMutableAttributedString*)changeLabelWithText2:(NSString*)needText andStartplace:(NSString *)startplace andendplae:(NSString *)endplace andfontsize:(float)fontsize
{
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:needText];
    NSInteger startlength = startplace.length;
    //起始格式化
    [attrString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"iconfont" size:fontsize+2] range:NSMakeRange(0,startlength)];
    //    //尾部格式化
    [attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontsize] range:NSMakeRange(startlength , needText.length  - startlength)];
    return attrString;
}
-(NSMutableAttributedString*)changeLabelWithText:(NSString*)needText andStartplace:(NSString *)startplace andendplae:(NSString *)endplace andfontsize:(float)fontsize
{
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:needText];
    NSInteger startlength = startplace.length;
    //起始格式化
    [attrString addAttribute:NSForegroundColorAttributeName value:COLORRGBA(102, 102, 102, 1) range:NSMakeRange(0,startlength)];
    //    //尾部格式化
    [attrString addAttribute:NSForegroundColorAttributeName value:COLORRGBA(153, 153, 153, 1) range:NSMakeRange(startlength , needText.length  - startlength)];
    return attrString;
}

- (void)enterClick:(UIButton *)btn{
    
    float fontsize = 17;
    
    fontsize = SCREEN_H < 667 ? 15 : 19;
    
    if (SCREEN_H == 667) {
        
        fontsize = 17;
    }
    
    switch (btn.tag) {
        case return_tag:
            //返回
            [self.navigationController popViewControllerAnimated:YES];
            break;
        case yanzheng_tag:
            //获取验证码
        {
            [self getYanzhengString];
            break;
        }
               case config_tag:
            //确认
        {
            if (messagetf.text.length == 0) {
                ALERT(@"提示", @"验证码格式有误", self, @"确定", nil);
                return;
            }
            [self configZhuanzhang];
            break;
        }
    }
}
#pragma mark  - -- - - 获取验证码- -- - - - - -

- (void)getYanzhengString{
    
        NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:USER_TOCKE];
        NSString * url = [NSString stringWithFormat:@"%@&token=%@&money=%@&type=%@",URL_GETCODE,token,_jinestring,_user_type];
//    NSString * url = [NSString stringWithFormat:@"%@&token=%@&money=%@&type=%@",URL_GETCODE,token,_jinestring,@1];

        NSLog(@"转账验证码 url %@",url);
        [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            if (responseObject) {
    
                NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
    
                NSInteger code = [dict[@"code"]integerValue];
    
                if (code == 0) {
                    //获取验证码成功
                    NSLog(@"get code ok");
                    //获取验证码成功 及相应充值参数
                    NSDictionary * info = dict[@"info"];
                    self.info = info;
                    NSLog(@"转账验证码info %@",self.info);
                    _sendcode = @"1";
                    //发送短信
                    [self loadTimer];
    
                }else{
    
                    NSLog(@"get code no");
                    ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                }
            }
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        }];
}
#pragma makr - - - - - - - - - - - - 确认转账 － － － － － － －－ － － － －
- (void)configZhuanzhang{
    
    if (![_sendcode isEqualToString:@"1"]) {
        ALERT(@"提示", @"请获取验证码", self, @"确定", nil);
        return;
    }
    NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:USER_TOCKE];
    NSString * url = [NSString stringWithFormat:@"%@&token=%@&code=%@&money=%@&desc=%@&type=%@",URL_CONFIGZHUAN,token,messagetf.text,_jinestring,_beizhutf,_zhifu_type];
    NSDictionary * param = [NSDictionary dictionaryWithDictionary:_userinfo];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:param options:0 error:nil];
    NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    url = [NSString stringWithFormat:@"%@&userInfo=%@",url,jsonString];
    
    NSDictionary * param1 = @{@"masterId":self.info[@"masterId"],
                             @"customerId":self.info[@"customerId"],
                             @"orderId":self.info[@"orderId"],
                             @"OpenId":self.info[@"OpenId"],
                             @"orderId":self.info[@"orderId"],
                             @"amount":self.info[@"amount"],
                             @"paydate":self.info[@"paydate"]};
    
    NSData *jsonData1 = [NSJSONSerialization dataWithJSONObject:param1 options:0 error:nil];
    NSString * jsonString1 = [[NSString alloc] initWithData:jsonData1 encoding:NSUTF8StringEncoding];
    url = [NSString stringWithFormat:@"%@&info=%@",url,jsonString1];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSLog(@"确认转账 url %@",url);
    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (responseObject) {
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSInteger code = [dict[@"code"]integerValue];
            if (code == 0) {
             //进入转账成功界面
                SuccedZhuanViewController * succedvc = [[SuccedZhuanViewController alloc]init];
                succedvc.jinestring = self.jinestring;
                succedvc.username = self.user_name;
                [self.navigationController pushViewController:succedvc  animated:YES];
                
            }else{
                NSLog(@"get code no");
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                
            }
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
    }];
    
}


- (void)loadTimer{
    
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [messbtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                [messbtn setTitleColor:COLORRGBA(255, 102, 102, 1) forState:UIControlStateNormal];
                messbtn.layer.cornerRadius = 2;
                messbtn.layer.borderColor = [COLORRGBA(255, 102, 102, 1)CGColor];
                messbtn.layer.borderWidth = 1;
                messbtn.clipsToBounds = YES;
                messbtn.backgroundColor = [UIColor whiteColor];
                messbtn.clipsToBounds = YES;
                
                messbtn.userInteractionEnabled = YES;
                
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果 %2d秒后重新发送
                [messbtn setTitle:[NSString stringWithFormat:@"已发送(%2ds)", seconds] forState:UIControlStateNormal];
                messbtn.layer.borderWidth = 0;
                messbtn.backgroundColor = COLORRGBA(238, 240, 239, 1);
                [messbtn setTitleColor:COLORRGBA(174, 174, 173, 1) forState:UIControlStateNormal];
                
                messbtn.userInteractionEnabled = NO;
            });
            time--;
            
        }
    });
    
    dispatch_resume(_timer);
    
    
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    [self.view endEditing:YES];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.view endEditing:YES];
    
}

- (AFHTTPSessionManager*)manger{
    
    if (!_manger) {
        
        _manger = [AFHTTPSessionManager manager];
        
        _manger.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        _manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    }
    return _manger;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
